package cn.itcast.controller;


import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.entity.Result;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import cn.itcast.utils.MD5Utils;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Reference
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 查询用户名
     */
    @GetMapping("/getUsername")
    public Result userLogin (){
        try {
            //通过SpringSecurity的域对象获取
            String username =  SecurityContextHolder.getContext().getAuthentication().getName();
            log.debug("从框架中获取的username:{}...........",username);
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(true, MessageConstant.GET_USERNAME_FAIL);
    }



    /**
     * 查询数据 : findPageUser
     * 模糊查询 : findUser
     * @return
     */
    @PreAuthorize("hasAnyAuthority('USER_QUERY')")
    @GetMapping(path = "/page")
    public Result findPage(QueryPageBean queryPageBean) {
        try {
            if (null == queryPageBean.getQueryString()) {
                //查询数据 : findPageUser
                PageResult pageResult = userService.findPageUser(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
                return new Result(true, MessageConstant.QUERY_USER_SUCCESS, pageResult);
            }else {
                //模糊查询 : findUser
                PageResult pageResult = userService.findUser(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());

                return new Result(true, MessageConstant.QUERY_USER_SUCCESS, pageResult);
            }

        } catch (
                Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     *  添加用户数据
     * @return
     */
    @PreAuthorize("hasAnyAuthority('USER_ADD')")
    @PostMapping
    @Transactional
    public Result insertUser(@RequestBody User user,
                             Integer[] roleIds) {
        try {
            log.info("添加用户 ==> user : {}",user);
            log.info("添加用户 ==> roleIds : {}",roleIds);
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            Boolean bool = userService.insertUser(user, roleIds);
            if (bool){
                return new Result(bool, MessageConstant.ADD_USER_SUCCESS);
            }
            return new Result(bool, MessageConstant.ADD_USER_FAIL);
        } catch (
                Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
    }



    /**
     * 编辑用户数据
     *
     * @return
     */
    @PreAuthorize("hasAnyAuthority('USER_EDIT')")
    @PutMapping
    @Transactional
    public Result updateUser(@RequestBody User user ,
                             Integer[] roleIds) {
        try {
	log.info("编辑用户 ==> user : {}",user);
            log.info("编辑用户 ==> roleIds : {}",roleIds);
            user.setPassword(passwordEncoder.encode(user.getPassword()));

            Boolean bool = userService.updateUser(user, roleIds);
            if (bool){
                return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
            }
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        } catch (
                Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        }
    }


    /**
     * 编辑回显数据
     * @param id
     * @return
     */
    @GetMapping(path = "/{id}")
    public Result findById(@PathVariable Integer id) {
        try {
            //编辑需要做回显,根据id查找数据库数据,显示在页面,然后对其修改
            User user = userService.findById(id);
	log.info("角色信息回显 ==> id : {}",id);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, user);
        } catch (
                Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 查询用户关联的角色项信息
     * @param id
     * @return
     */
    @GetMapping(path = "/{id}/roleIds")
    public Result findCheckGroupById(@PathVariable Integer id) {
        try {
            //查询用户关联的角色项信息
            log.info("id ==> {}",id);
            Integer[] roleId = userService.findRoleId(id);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS,roleId);
        } catch (
                Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 删除数据
     *
     * @return
     */
    @PreAuthorize("hasAnyAuthority('USER_DELETE')")
    @DeleteMapping(path = "/{id}")
    @Transactional
    public Result deleteUser(@PathVariable Integer id) {
        try {
	log.info("删除用户 ==> id : {}",id);
            userService.deleteUser(id);
            return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
        } catch (
                Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_USER_FAIL);
        }
    }
}
